<?php

namespace app\common\model;

use think\Cache;
use app\common\model\BaseModel;

/**
 * 抽奖设置
 * Class Setting
 * @package app\common\model\price
 */
class PriceSetting extends BaseModel
{
    protected $name = 'price_setting';
    protected $createTime = false;

    /**
     * 设置项描述
     * @var array
     */
    private $describe = [
        'basic' => '基础设置',
    ];

    /**
     * 更新系统设置
     * @param $key
     * @param $values
     * @return bool
     * @throws \think\exception\DbException
     */
    public function edit($key, $values)
    {
        $model = self::detail($key) ?: $this;
        // 删除系统设置缓存
        Cache::rm('price_setting_' . self::$wxapp_id);
        return $model->save([
                'key' => $key,
                'describe' => $this->describe[$key],
                'values' => $values,
                'wxapp_id' => self::$wxapp_id,
            ]) !== false;
    }


    /**
     * 获取器: 转义数组格式
     */
    public function getValuesAttr($value)
    {
        return json_decode($value, true);
    }

    /**
     * 修改器: 转义成json格式
     */
    public function setValuesAttr($value)
    {
        return json_encode($value);
    }

    /**
     * 获取指定项设置
     */
    public static function getItem($key, $wxapp_id = null)
    {
        $data = static::getAll($wxapp_id);
        return isset($data[$key]) ? $data[$key]['values'] : [];
    }

    /**
     * 获取全部设置
     */
    public static function getAll($wxapp_id = null)
    {
        $model = new static;
        is_null($wxapp_id) && $wxapp_id = $model::$wxapp_id;
        if (!$data = Cache::get('price_setting_' . $wxapp_id)) {
            $data = array_column(collection($model::all())->toArray(), null, 'key');
            Cache::tag('cache')->set('price_setting_' . $wxapp_id, $data);
        }
        return array_merge_multiple($model->defaultData(), $data);
    }

     /**
     * 获取设置项信息
     */
    public static function detail($key)
    {
        return static::get(compact('key'));
    }

     /**
     * 默认配置
     * @return array
     */
    public function defaultData()
    {
        return [
            'basic' => [
                'key' => 'basic',
                'describe' => '价格区间',
                'values' => [
                    '1' =>'0-100',
                    '2' =>'100-500',
                    '3' =>'500-1000',
                    '4' =>'1000-2000',
                    '5' =>'2000-5000',
                ]
            ]
        ];
    }

}